<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能报表分析系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #0f1419 0%, #1a2332 100%);
            min-height: 100vh;
            color: #e0e0e0;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: #0d1117;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.4);
            overflow: hidden;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, #161b22 0%, #21262d 100%);
            color: #ecf0f1;
            padding: 40px 30px;
            text-align: center;
            position: relative;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, rgba(52, 152, 219, 0.05), rgba(155, 89, 182, 0.05));
            pointer-events: none;
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.8em;
            font-weight: 300;
            position: relative;
            z-index: 1;
        }
        
        .header p {
            margin: 15px 0 0 0;
            opacity: 0.9;
            font-size: 1.2em;
            position: relative;
            z-index: 1;
        }
        
        .content {
            padding: 40px;
            background: #0d1117;
        }
        
        .form-section {
            margin-bottom: 40px;
        }
        
        .form-section h2 {
            color: #ecf0f1;
            font-size: 1.8em;
            margin-bottom: 25px;
            font-weight: 400;
        }
        
        .form-group {
            margin-bottom: 25px;
            position: relative;
        }
        
        label {
            display: block;
            margin-bottom: 12px;
            font-weight: 500;
            color: #bdc3c7;
            font-size: 1.1em;
        }
        
        .input-container {
            position: relative;
            margin-bottom: 25px;
        }
        
        textarea {
            width: 100%;
            padding: 15px 18px 60px 18px;
            background: #161b22;
            border: 2px solid #30363d;
            border-radius: 12px;
            color: #e0e0e0;
            font-size: 16px;
            font-family: inherit;
            resize: vertical;
            min-height: 120px;
            transition: all 0.3s ease;
        }
        
        textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .analyze-button-container {
            position: absolute;
            bottom: 15px;
            right: 15px;
            z-index: 10;
        }
        
        .analyze-button-container button {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
        }
        
        .analyze-button-container button:hover {
            background: linear-gradient(135deg, #2980b9 0%, #3498db 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
        
        .analyze-button-container button:disabled {
            background: #34495e;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .mode-selector {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .mode-selector label {
            margin-bottom: 0;
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            padding: 8px 16px;
            background: #161b22;
            border-radius: 8px;
            border: 2px solid #30363d;
            transition: all 0.3s ease;
        }
        
        .mode-selector label:hover {
            border-color: #3498db;
        }
        
        .mode-selector input[type="radio"] {
            margin: 0;
        }
        
        .mode-selector input[type="radio"]:checked + span {
            color: #3498db;
        }
        
        .examples {
            margin-bottom: 30px;
        }
        
        .examples h3 {
            color: #ecf0f1;
            margin-bottom: 15px;
            font-size: 1.2em;
        }
        
        .example-btn {
            background: #21262d;
            color: #bdc3c7;
            border: 1px solid #30363d;
            padding: 10px 16px;
            margin: 5px 8px 5px 0;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .example-btn:hover {
            background: #30363d;
            color: #ecf0f1;
            border-color: #3498db;
        }
        
        .workflow-info {
            background: #161b22;
            border-radius: 12px;
            border: 1px solid #30363d;
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .workflow-header {
            padding: 20px 25px;
            background: #21262d;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.3s ease;
        }
        
        .workflow-header:hover {
            background: #2d333b;
        }
        
        .workflow-header h3 {
            color: #ecf0f1;
            margin: 0;
            font-size: 1.3em;
        }
        
        .workflow-toggle {
            font-size: 1.2em;
            transition: transform 0.3s ease;
            color: #bdc3c7;
        }
        
        .workflow-content {
            padding: 0;
            max-height: 0;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .workflow-content.expanded {
            max-height: 500px;
            padding: 25px;
        }
        
        .workflow-step {
            margin-bottom: 20px;
            padding: 15px;
            background: #0d1117;
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }
        
        .step-number {
            font-weight: 600;
            color: #3498db;
            margin-bottom: 8px;
        }
        
        .step-description {
            color: #bdc3c7;
            font-size: 0.95em;
        }
        
        .progress-section {
            margin-bottom: 30px;
            display: none;
        }
        
        .progress-step {
            padding: 15px 20px;
            margin-bottom: 10px;
            background: #161b22;
            border-radius: 8px;
            border-left: 4px solid #6c757d;
            transition: all 0.3s ease;
        }
        
        .progress-step.processing {
            border-left-color: #f39c12;
            background: #21262d;
        }
        
        .progress-step.success {
            border-left-color: #2ecc71;
        }
        
        .progress-step.error {
            border-left-color: #e74c3c;
        }
        
        .progress-step-title {
            font-weight: 600;
            color: #ecf0f1;
            margin-bottom: 5px;
        }
        
        .progress-step-message {
            color: #bdc3c7;
            font-size: 0.9em;
        }
        
        .results {
            margin-top: 30px;
        }
        
        .results h2 {
            color: #ecf0f1;
            font-size: 1.8em;
            margin-bottom: 25px;
            font-weight: 400;
        }
        
        .result-section {
            background: #161b22;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            border: 1px solid #30363d;
        }
        
        .result-section h3 {
            color: #ecf0f1;
            margin-bottom: 15px;
            font-size: 1.3em;
        }
        
        .code-block {
            background: #0d1117;
            border: 1px solid #21262d;
            border-radius: 8px;
            padding: 20px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            color: #e0e0e0;
            overflow-x: auto;
            white-space: pre-wrap;
        }
        
        .html-report-container {
            width: 100%;
            border: 1px solid #30363d;
            border-radius: 12px;
            background: white;
            overflow: hidden;
            position: relative;
        }
        
        .html-report-container iframe {
            width: 100%;
            height: 800px;
            border: none;
            min-height: 600px;
        }
        
        .report-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .action-btn:hover {
            background: linear-gradient(135deg, #2980b9 0%, #3498db 100%);
            transform: translateY(-1px);
        }
        
        .action-btn.secondary {
            background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
        }
        
        .action-btn.secondary:hover {
            background: linear-gradient(135deg, #7f8c8d 0%, #95a5a6 100%);
        }
        
        .copy-success {
            color: #2ecc71;
            font-size: 12px;
            margin-left: 10px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .copy-success.show {
            opacity: 1;
        }
        
        .success {
            color: #2ecc71;
            font-weight: 600;
            padding: 15px;
            background: rgba(46, 204, 113, 0.1);
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .error {
            color: #e74c3c;
            font-weight: 600;
            padding: 15px;
            background: rgba(231, 76, 60, 0.1);
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #bdc3c7;
        }
        
        .loading::after {
            content: '...';
            animation: dots 1.5s steps(4, end) infinite;
        }
        
        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }
        
        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 15px;
            }
            
            .content {
                padding: 20px;
            }
            
            .header {
                padding: 30px 20px;
            }
            
            .header h1 {
                font-size: 2.2em;
            }
            
            .examples {
                text-align: left;
            }
            
            .example-btn {
                display: block;
                margin: 8px 0;
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>智能报表分析系统</h1>
            <p>基于AutoGen的智能数据分析和可视化平台</p>
        </div>
        
        <div class="content">
            <div class="form-section">
                <h2>数据分析需求</h2>
                
                <div class="mode-selector">
                    <label>
                        <input type="radio" name="mode" value="stream" checked>
                        <span>流式分析 (推荐)</span>
                    </label>
                    <label>
                        <input type="radio" name="mode" value="batch">
                        <span>批量分析</span>
                    </label>
                </div>
                
                <div class="input-container">
                    <label for="query">请描述您的数据分析需求：</label>
                    <textarea 
                        id="query" 
                        placeholder="例如：帮我分析2024年1月到6月的财务情况，或者分析最近30天的用户活跃度..."
                        required
                    ></textarea>
                    <div class="analyze-button-container">
                        <button id="analyzeBtn" onclick="analyzeData()">开始分析</button>
                    </div>
                </div>
                
                <div class="examples">
                    <h3>示例查询：</h3>
                    <button class="example-btn" onclick="setQuery('帮我分析2024年1月到6月的财务情况')">财务分析</button>
                    <button class="example-btn" onclick="setQuery('分析最近30天的用户活跃度')">用户活跃度</button>
                    <button class="example-btn" onclick="setQuery('统计最近3个月的销售数据')">销售数据</button>
                    <button class="example-btn" onclick="setQuery('查看产品库存情况')">库存分析</button>
                    <button class="example-btn" onclick="setQuery('分析最近6个月的客户满意度')">客户满意度</button>
                </div>
                
                <div class="workflow-info">
                    <div class="workflow-header" onclick="toggleWorkflow()">
                        <h3>工作流程</h3>
                        <span class="workflow-toggle">▼</span>
                    </div>
                    <div class="workflow-content">
                        <div class="workflow-step">
                            <div class="step-number">步骤1: 获取数据库表结构</div>
                            <div class="step-description">系统首先查询数据库中所有表的结构信息</div>
                        </div>
                        <div class="workflow-step">
                            <div class="step-number">步骤2: 分析用户需求并选择相关表</div>
                            <div class="step-description">AI分析用户需求，从所有表中选择最相关的表</div>
                        </div>
                        <div class="workflow-step">
                            <div class="step-number">步骤3: 获取选定表的字段信息</div>
                            <div class="step-description">获取选定表的详细字段信息，确保SQL准确性</div>
                        </div>
                        <div class="workflow-step">
                            <div class="step-number">步骤4: 根据字段信息生成SQL查询</div>
                            <div class="step-description">基于准确的字段信息生成SQL查询语句</div>
                        </div>
                        <div class="workflow-step">
                            <div class="step-number">步骤5: 执行SQL查询</div>
                            <div class="step-description">执行生成的SQL查询，获取数据结果</div>
                        </div>
                        <div class="workflow-step">
                            <div class="step-number">步骤6: 生成HTML报告</div>
                            <div class="step-description">生成包含1-3种不同维度图表的完整HTML可视化报告</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div id="progressSection" class="progress-section">
                <h2>分析进度</h2>
                <div id="progressSteps"></div>
            </div>
            
            <div id="results" class="results" style="display: none;">
                <h2>分析结果</h2>
                <div id="resultContent"></div>
            </div>
        </div>
    </div>

    <script>
        function setQuery(query) {
            document.getElementById('query').value = query;
        }

        function toggleWorkflow() {
            const content = document.querySelector('.workflow-content');
            const toggle = document.querySelector('.workflow-toggle');
            
            if (content.classList.contains('expanded')) {
                content.classList.remove('expanded');
                toggle.textContent = '▼';
            } else {
                content.classList.add('expanded');
                toggle.textContent = '▲';
            }
        }

        function getSelectedMode() {
            const modeRadios = document.querySelectorAll('input[name="mode"]');
            for (let radio of modeRadios) {
                if (radio.checked) {
                    return radio.value;
                }
            }
            return 'stream';
        }

        async function analyzeData() {
            const query = document.getElementById('query').value.trim();
            if (!query) {
                alert('请输入分析需求');
                return;
            }

            const mode = getSelectedMode();
            
            if (mode === 'stream') {
                await analyzeDataStream(query);
            } else {
                await analyzeDataBatch(query);
            }
        }

        async function analyzeDataStream(query) {
            const analyzeBtn = document.getElementById('analyzeBtn');
            const progressSection = document.getElementById('progressSection');
            const resultsDiv = document.getElementById('results');
            const progressSteps = document.getElementById('progressSteps');

            // 显示加载状态
            analyzeBtn.disabled = true;
            analyzeBtn.textContent = '分析中...';
            progressSection.style.display = 'block';
            resultsDiv.style.display = 'none';
            progressSteps.innerHTML = '';

            try {
                const response = await fetch('http://localhost:8000/analyze/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                    },
                    body: JSON.stringify({
                        query: query
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (let line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.substring(6);
                                const data = JSON.parse(jsonStr);
                                handleStreamData(data);
                            } catch (e) {
                                console.error('解析流数据失败:', e);
                                console.error('原始数据:', line.substring(6));
                                
                                // 尝试显示错误信息给用户
                                const errorData = {
                                    step: "error",
                                    status: "error",
                                    error: `JSON解析失败: ${e.message}`,
                                    message: "数据解析失败，请重试"
                                };
                                handleStreamData(errorData);
                            }
                        }
                    }
                }
            } catch (error) {
                displayError('网络错误：' + error.message);
            } finally {
                analyzeBtn.disabled = false;
                analyzeBtn.textContent = '开始分析';
            }
        }

        function handleStreamData(data) {
            const progressSteps = document.getElementById('progressSteps');
            const resultsDiv = document.getElementById('results');
            
            // 更新进度步骤
            updateProgressStep(data);
            
            // 如果完成，显示最终结果
            if (data.step === 'complete' && data.status === 'success') {
                displayStreamResults(data);
                resultsDiv.style.display = 'block';
            } else if (data.step === 'error' || data.status === 'error') {
                displayError(data.error || data.message || '分析失败');
                resultsDiv.style.display = 'block';
            }
        }

        function updateProgressStep(data) {
            const progressSteps = document.getElementById('progressSteps');
            const stepId = `step-${data.step}`;
            
            let stepElement = document.getElementById(stepId);
            if (!stepElement) {
                stepElement = document.createElement('div');
                stepElement.id = stepId;
                stepElement.className = 'progress-step';
                progressSteps.appendChild(stepElement);
            }
            
            // 清除之前的状态类
            stepElement.classList.remove('processing', 'success', 'error');
            
            // 添加当前状态类
            if (data.status === 'processing') {
                stepElement.classList.add('processing');
            } else if (data.status === 'success') {
                stepElement.classList.add('success');
            } else if (data.status === 'error') {
                stepElement.classList.add('error');
            }
            
            const stepNames = {
                'start': '开始分析',
                'table_info': '获取表结构',
                'table_selection': '选择相关表',
                'field_info': '获取字段信息',
                'sql_generation': '生成SQL查询',
                'sql_execution': '执行SQL查询',
                'html_generation': '生成HTML报告',
                'complete': '分析完成',
                'error': '错误'
            };
            
            stepElement.innerHTML = `
                <div class="progress-step-title">${stepNames[data.step] || data.step}</div>
                <div class="progress-step-message">${data.message || ''}</div>
            `;
        }

        function displayStreamResults(result) {
            const resultContent = document.getElementById('resultContent');
            
            let html = '<div class="success">分析完成！</div>';
            
            // SQL查询
            if (result.sql_query) {
                html += `
                    <div class="result-section">
                        <h3>生成的SQL查询</h3>
                        <div class="code-block">${result.sql_query}</div>
                    </div>
                `;
            }
            
            // 查询数据
            if (result.data) {
                html += `
                    <div class="result-section">
                        <h3>查询数据</h3>
                        <div class="code-block">${JSON.stringify(result.data, null, 2)}</div>
                    </div>
                `;
            }
            
                         // HTML报告
             if (result.html_report) {
                 html += `
                     <div class="result-section">
                         <h3>可视化报告</h3>
                         <div class="report-actions">
                             <button class="action-btn" onclick="copyHtmlReport()">
                                 📋 复制HTML
                             </button>
                             <button class="action-btn secondary" onclick="exportToPdf()">
                                 📄 导出PDF
                             </button>
                             <button class="action-btn secondary" onclick="downloadHtml()">
                                 💾 下载HTML
                             </button>
                             <span class="copy-success" id="copySuccess">复制成功！</span>
                         </div>
                         <div class="html-report-container">
                             <iframe id="reportIframe" srcdoc="${decodeHtmlReport(result)}" sandbox="allow-scripts"></iframe>
                         </div>
                     </div>
                 `;
             }
            
            resultContent.innerHTML = html;
        }

        async function analyzeDataBatch(query) {
            const analyzeBtn = document.getElementById('analyzeBtn');
            const resultsDiv = document.getElementById('results');
            const resultContent = document.getElementById('resultContent');
            const progressSection = document.getElementById('progressSection');

            // 显示加载状态
            analyzeBtn.disabled = true;
            analyzeBtn.textContent = '分析中...';
            resultsDiv.style.display = 'block';
            progressSection.style.display = 'none';
            resultContent.innerHTML = '<div class="loading">正在分析数据，请稍候</div>';

            try {
                const response = await fetch('http://localhost:8000/analyze', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        query: query
                    })
                });

                const result = await response.json();

                if (response.ok) {
                    displayBatchResults(result);
                } else {
                    displayError(result.detail || '分析失败');
                }
            } catch (error) {
                displayError('网络错误：' + error.message);
            } finally {
                analyzeBtn.disabled = false;
                analyzeBtn.textContent = '开始分析';
            }
        }

        function displayBatchResults(result) {
            const resultContent = document.getElementById('resultContent');
            
            let html = '';
            
            if (result.status === 'success') {
                html += '<div class="success">分析完成！</div>';
                
                // SQL查询
                if (result.sql_query) {
                    html += `
                        <div class="result-section">
                            <h3>生成的SQL查询</h3>
                            <div class="code-block">${result.sql_query}</div>
                        </div>
                    `;
                }
                
                // 查询数据
                if (result.data) {
                    html += `
                        <div class="result-section">
                            <h3>查询数据</h3>
                            <div class="code-block">${JSON.stringify(result.data, null, 2)}</div>
                        </div>
                    `;
                }
                
                                 // HTML报告
                 if (result.html_report) {
                     html += `
                         <div class="result-section">
                             <h3>可视化报告</h3>
                             <div class="report-actions">
                                 <button class="action-btn" onclick="copyHtmlReport()">
                                     📋 复制HTML
                                 </button>
                                 <button class="action-btn secondary" onclick="exportToPdf()">
                                     📄 导出PDF
                                 </button>
                                 <button class="action-btn secondary" onclick="downloadHtml()">
                                     💾 下载HTML
                                 </button>
                                 <span class="copy-success" id="copySuccess">复制成功！</span>
                             </div>
                                                      <div class="html-report-container">
                             <iframe id="reportIframe" srcdoc="${decodeHtmlReport(result)}" sandbox="allow-scripts"></iframe>
                         </div>
                         </div>
                     `;
                 }
                
                // 兼容旧的chart_config格式
                if (result.chart_config && !result.html_report) {
                    html += `
                        <div class="result-section">
                            <h3>图表配置</h3>
                            <div class="code-block">${result.chart_config}</div>
                        </div>
                    `;
                }
            } else {
                html += `<div class="error">分析失败：${result.error || '未知错误'}</div>`;
            }
            
            resultContent.innerHTML = html;
        }

        function displayError(message) {
            const resultContent = document.getElementById('resultContent');
            const resultsDiv = document.getElementById('results');
            resultsDiv.style.display = 'block';
            resultContent.innerHTML = `<div class="error">${message}</div>`;
        }

                         function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
        
        // 解码HTML报告
        function decodeHtmlReport(result) {
            if (result.html_encoded && result.html_report) {
                try {
                    // 解码base64编码的HTML
                    const decodedHtml = atob(result.html_report);
                    return decodedHtml;
                } catch (error) {
                    console.error('HTML解码失败:', error);
                    return result.html_report; // 如果解码失败，返回原始内容
                }
            }
            return result.html_report || '';
        }
         
         // 复制HTML报告
         async function copyHtmlReport() {
             try {
                 const iframe = document.getElementById('reportIframe');
                 if (!iframe) {
                     alert('未找到报告内容');
                     return;
                 }
                 
                 // 获取iframe的srcdoc内容
                 const htmlContent = iframe.getAttribute('srcdoc');
                 
                 // 复制到剪贴板
                 await navigator.clipboard.writeText(htmlContent);
                 
                 // 显示成功消息
                 const copySuccess = document.getElementById('copySuccess');
                 copySuccess.classList.add('show');
                 setTimeout(() => {
                     copySuccess.classList.remove('show');
                 }, 2000);
                 
             } catch (error) {
                 console.error('复制失败:', error);
                 alert('复制失败，请手动复制');
             }
         }
         
         // 下载HTML文件
         function downloadHtml() {
             try {
                 const iframe = document.getElementById('reportIframe');
                 if (!iframe) {
                     alert('未找到报告内容');
                     return;
                 }
                 
                 const htmlContent = iframe.getAttribute('srcdoc');
                 const blob = new Blob([htmlContent], { type: 'text/html' });
                 const url = URL.createObjectURL(blob);
                 
                 const a = document.createElement('a');
                 a.href = url;
                 a.download = `数据分析报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.html`;
                 document.body.appendChild(a);
                 a.click();
                 document.body.removeChild(a);
                 URL.revokeObjectURL(url);
                 
             } catch (error) {
                 console.error('下载失败:', error);
                 alert('下载失败');
             }
         }
         
         // 导出PDF
         async function exportToPdf() {
             try {
                 const iframe = document.getElementById('reportIframe');
                 if (!iframe) {
                     alert('未找到报告内容');
                     return;
                 }
                 
                 // 检查是否支持html2pdf
                 if (typeof html2pdf === 'undefined') {
                     // 动态加载html2pdf库
                     await loadHtml2Pdf();
                 }
                 
                 // 获取iframe内容
                 const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                 const element = iframeDoc.body;
                 
                 const opt = {
                     margin: 1,
                     filename: `数据分析报告_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.pdf`,
                     image: { type: 'jpeg', quality: 0.98 },
                     html2canvas: { 
                         scale: 2,
                         useCORS: true,
                         allowTaint: true
                     },
                     jsPDF: { 
                         unit: 'in', 
                         format: 'a4', 
                         orientation: 'portrait' 
                     }
                 };
                 
                 // 生成PDF
                 await html2pdf().set(opt).from(element).save();
                 
             } catch (error) {
                 console.error('PDF导出失败:', error);
                 alert('PDF导出失败，请尝试下载HTML文件');
             }
         }
         
         // 动态加载html2pdf库
         async function loadHtml2Pdf() {
             return new Promise((resolve, reject) => {
                 if (typeof html2pdf !== 'undefined') {
                     resolve();
                     return;
                 }
                 
                 const script = document.createElement('script');
                 script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';
                 script.onload = resolve;
                 script.onerror = reject;
                 document.head.appendChild(script);
             });
         }
    </script>
</body>
</html>
</html> 
</html> 